package com.pipe.protocol.events.write;

import com.pipe.util.IntegerConveter;
import com.pipe.util.MyBytebufUtil;
import io.netty.buffer.ByteBuf;

/**
 * @author Kiven
 */
public class WriteRowEventV2Header {

    /**
     * If the table id is 0x00ffffff it is a dummy event that
     * should have the end of statement flag set that declares
     * that all table maps can be freed. Otherwise it refers to
     * a table defined by TABLE_MAP_EVENT.
     */
    private long tableId;
    private int flags;
    private int extraDataLength;
    private String extraData;

    public WriteRowEventV2Header(long tableId, int flags, int extraDataLength, String extraData) {
        this.tableId = tableId;
        this.flags = flags;
        this.extraDataLength = extraDataLength;
        this.extraData = extraData;
    }

    public static WriteRowEventV2Header build(ByteBuf byteBuf){
        byte[] tableId = new byte[6];
        byteBuf.readBytes(tableId);
        long ti = IntegerConveter.getLongFromByte(tableId);
        int f = byteBuf.readUnsignedShortLE();
        int edl = byteBuf.readUnsignedShortLE();
        /**extra_data [length=extra_data_len - 2]*/
        String ed = MyBytebufUtil.readStringFromBytebuf(byteBuf, edl - 2);
        return new WriteRowEventV2Header(ti, f, edl, ed);
    }

    @Override
    public String toString() {
        return "WriteRowEventV2Header{" +
                "tableId=" + tableId +
                ", flags=" + flags +
                ", extraDataLength=" + extraDataLength +
                ", extraData='" + extraData + '\'' +
                '}';
    }
}